<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>浏览器存储</title>
</head>

<body>
    <h2>localStorage本地存储</h2>
    <button onclick="saveLocal()">点我存储本地数据</button>
    <button onclick="readLocal()">读取本地数据</button>
    <button onclick="deleteLocal()">删除本地数据</button>
    <button onclick="clearLocal()">清空本地数据</button>
    <hr>
    <h2>sessionStorage会话存储</h2>
    <button onclick="sessionSaveLocal()">点我存储会话数据</button>
    <button onclick="sessionReadLocal()">读取会话数据</button>
    <button onclick="sessionDeleteLocal()">删除会话数据</button>
    <button onclick="sessionClearLocal()">清空会话数据</button>

    <script>
        let person = { "userName": "杨丹妮", "age": 20, "hobby": "打游戏" };
        //存储数据，Window 关键字可以省略，默认是 window 作用域
        function saveLocal() {
            window.localStorage.setItem("userName", "林舒婷");
            localStorage.setItem("age", 18);
            localStorage.setItem("hobby", "写代码");
            localStorage.setItem("person", JSON.stringify(person));
        }

        //读取数据
        function readLocal() {
            console.log(localStorage.getItem("userName"));
            console.log(localStorage.getItem("age"));
            console.log(localStorage.getItem("hobby"));
            const person = JSON.parse(localStorage.getItem("person"));
            console.log(person);
        }

        //删除
        function deleteLocal() {
            localStorage.removeItem("userName");
            localStorage.removeItem("age");
            localStorage.removeItem("hobby");
            localStorage.removeItem("person");
        }

        //清空
        function clearLocal() {
            localStorage.clear();
        }
    </script>

    <script>
        let sessionPerson = { "userName": "靓仔", "income": "2万", "hobby": "夜跑" };
        //存储数据，Window 关键字可以省略，默认是 window 作用域
        function sessionSaveLocal() {
            window.sessionStorage.setItem("skill", "撩妹");
            sessionStorage.setItem("sessionPerson", JSON.stringify(sessionPerson));
        }

        //读取数据
        function sessionReadLocal() {
            console.log(sessionStorage.getItem("skill"));
            const sessionPerson = JSON.parse(sessionStorage.getItem("sessionPerson"));
            console.log(sessionPerson);
        }

        //删除
        function sessionDeleteLocal() {
            sessionStorage.removeItem("skill");
            sessionStorage.removeItem("sessionPerson");
        }

        //清空
        function sessionClearLocal() {
            sessionStorage.clear();
        }
    </script>
</body>

</html>